# -*- coding: utf-8 -*-
#
# The Philatelist program is a fork of the OpenNumismat program
# Copyright (c) 2011 - 2024 Vitaly Ignatov (OpenNumismat) <opennumismat@gmail.com>
# Copyright (c) 2021 - 2024 Victor Nabatov (Philatelist) <nabatov.victor@gmail.com>
#

from PySide6.QtCore import Qt, QDate
from PySide6.QtWidgets import (
    QAbstractSpinBox, QCheckBox, QDateTimeEdit, QDoubleSpinBox,
    QLabel, QLineEdit, QSizePolicy, QSpinBox, QTextEdit
)
from Philatelist.StampEditor.FormItems import *
from Philatelist.StampEditor.ImageLabel import ImageEdit
from Philatelist.Collection.CollectionFields import FieldTypes as Type


class FormItem(object):

    def __init__(self, settings, field, title, itemType, section=None, reference=None, parent=None):
        self.reference = reference
        self._field = field
        self._title = title
        if itemType & Type.Checkable:
            self._label = QCheckBox(title, parent)
            self._label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
            self._label.stateChanged.connect(self.checkBoxChanged)
        else:
            self._label = QLabel(title, parent)
            self._label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)

        self._type = itemType & Type.Mask
        if self._type == Type.String:
            if section:
                self._widget = LineEditRef(section, parent)
            else:
                if self._field in ('url', 'buying_invoice', 'sale_invoice'):
                    self._widget = UrlLineEdit(settings, parent)
                else:
                    self._widget = LineEdit(parent)

        elif self._type == Type.ShortString:
            if section:
                self._widget = LineEditRef(section, parent)

            elif self._field == 'rating':
                self._widget = RatingEdit(settings['stars_count'], parent)
            else:
                self._widget = ShortLineEdit(parent)

        elif self._type == Type.Number:
            if settings['free_numeric']:
                self._widget = UserNumericEdit(parent)
            else:
                self._widget = NumberEdit(parent)

        elif self._type == Type.BigInt:
            if settings['free_numeric']:
                self._widget = UserNumericEdit(parent)
            else:
                self._widget = BigIntEdit(parent)

        elif self._type == Type.Money:
            if settings['free_numeric']:
                self._widget = UserNumericEdit(parent)
            else:
                self._widget = MoneyEdit(parent)

        elif self._type == Type.Text:
            if itemType & Type.Disabled:
                if settings['rich_text']:
                    self._widget = RichTextBrowser(parent)
                else:
                    self._widget = TextBrowser(parent)
            else:
                if settings['rich_text']:
                    self._widget = RichTextEdit(parent)
                else:
                    self._widget = TextEdit(parent)

        elif self._type == Type.Image:
            self._widget = ImageEdit(field, self._label, parent)

        elif self._type == Type.Date:
            self._widget = DateEdit(parent)

        elif self._type == Type.Status:
            if itemType & Type.Disabled:
                self._widget = StatusBrowser(parent)
            else:
                self._widget = StatusEdit(settings, parent)

        elif self._type == Type.DateTime:
            self._widget = QDateTimeEdit(parent)

        elif self._type == Type.Char:
            self._widget = CharEdit(parent)
        else:
            raise TypeError

        if itemType & Type.Disabled:
            if self._type == Type.Image:
                self._widget.setDisabled(True)
            else:
                self._widget.setReadOnly(True)

        if itemType & Type.Checkable:
            # Disable fields with unchecked labels
            self._widget.setDisabled(True)

        self.hidden = False

    def setHidden(self):
        self.hidden = True

    def isHidden(self):
        return self.hidden

    def checkBoxChanged(self, state):
        self._widget.setDisabled(state == Qt.Unchecked)

    def field(self):
        return self._field

    def title(self):
        return self._title

    def label(self):
        return self._label

    def type(self):
        return self._type

    def widget(self):
        return self._widget

    def setWidget(self, widget):
        self._widget = widget

    def value(self):
        if isinstance(self._widget, QDateTimeEdit):
            date = self._widget.date()
            if date == self._widget.DEFAULT_DATE:
                return ''
            else:
                return date.toString(Qt.ISODate)

        elif isinstance(self._widget, QAbstractSpinBox):
            return self._widget.value()

        elif isinstance(self._widget, ImageEdit):
            return self._widget.data()

        elif isinstance(self._widget, StatusEdit):
            return self._widget.data()
        else:
            return self._widget.text()

    def setValue(self, value):
        if isinstance(self._widget, ImageEdit):
            if value:
                self._widget.loadFromFile(value)

        elif isinstance(self._widget, QSpinBox):
            self._widget.setText(value)

        elif isinstance(self._widget, QDoubleSpinBox):
            self._widget.setValue(float(value))

        elif isinstance(self._widget, QDateTimeEdit):
            value = str(value)
            if value:
                self._widget.setDate(QDate.fromString(str(value), Qt.ISODate))
            else:
                self._widget.setDate(self._widget.DEFAULT_DATE)
                lineEdit = self._widget.findChild(QLineEdit)
                lineEdit.setText("")

        elif isinstance(self._widget, StatusEdit):
            self._widget.setCurrentValue(value)

        elif isinstance(self._widget, StatusBrowser):
            self._widget.setCurrentValue(value)

        elif isinstance(self._widget, QTextEdit):
            self._widget.setText(str(value))

        elif isinstance(self._widget, LineEdit):
            self._widget.setText(str(value))
            self._widget.home(False)
            if self.reference:
                for act in self._widget.actions():
                    self._widget.removeAction(act)

                icon = self.reference.getIcon(self._field, str(value))
                if icon:
                    self._widget.addAction(icon, QLineEdit.LeadingPosition)
        else:
            value = str(value)
            self._widget.setText(value)
            self._widget.home(False)


    def clear(self):
        self._widget.clear()
